package com.dong.vedio.vedio2;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Service;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class UdpVideo2ReceiverService {
    // UDP监听端口
    private static final int UDP_PORT = 5002;
    // 视频帧缓冲区大小（根据实际帧大小调整）
    private static final int BUFFER_SIZE = 1024 * 1024; // 1MB
    private DatagramSocket datagramSocket;
    private ExecutorService executor;
    private boolean running = false;
    public   byte[] frameData;
    @PostConstruct
    public void start() {
        try {
            datagramSocket = new DatagramSocket(new InetSocketAddress(UDP_PORT));
            running = true;
            executor = Executors.newSingleThreadExecutor();
            executor.execute(this::receiveUdpPackets);
            System.out.println("UDP视频接收服务已启动，监听端口: " + UDP_PORT);
        } catch (Exception e) {
            System.err.println("启动UDP服务失败: " + e.getMessage());
        }
    }

    private void receiveUdpPackets() {
        byte[] buffer = new byte[BUFFER_SIZE];
        while (running) {
            try {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                datagramSocket.receive(packet); // 阻塞等待接收

                // 新增日志：打印收到的UDP数据大小和来源
//                System.out.println("收到UDP数据：" + packet.getLength() + "字节，来自：" + packet.getAddress().getHostAddress());

                frameData = new byte[packet.getLength()];
                System.arraycopy(buffer, 0, frameData, 0, packet.getLength());
                Video2WebSocketHandler.broadcastFrame(frameData);
            } catch (Exception e) {
                if (running) {
                    System.err.println("UDP接收错误: " + e.getMessage());
                }
            }
        }
    }

    @PreDestroy
    public void stop() {
        running = false;
        if (datagramSocket != null && !datagramSocket.isClosed()) {
            datagramSocket.close();
        }
        if (executor != null && !executor.isTerminated()) {
            executor.shutdown();
        }
        System.out.println("UDP视频接收服务已停止");
    }
}